﻿

using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using IotClientService;
using IotClientService.Consts;
using IotClientService.Extensions;
using IotClientService.Models.Lg.Remote;
using IotContract.Dtos.Remotes.Request;
using IotContract.Dtos.Remotes.Response;
using IotContract.Dtos.Servers.Process;
using IotContract.Dtos.Servers.Process.F29;
using IotContract.Enums;
using IotContract.Interfaces.Process;
using IotContract.Models.Clients.Hks;
using IotContract.Models.Jobs.F29;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using XT.Common.Config;
using XT.Common.Extensions;
using XT.Common.Models.Server;
using XT.Common.Services;

namespace IotClientWeb.Controllers;
/// <summary>
/// FMS远程调度接口，设备服务端提交数据或者向FMS请求数据
/// 托盘提交等
/// </summary>
[ApiDescriptionSettings(IotApiConst.FMS_PROCESS)]
[Route("fms/api/process")]
[AllowAnonymous]
public class FMSProcessService:ApiConfigService,  IDynamicApiController, ITransient
{
    private string _apiHead = "api";

    public FMSProcessService(IHttpClientFactory httpClientFactory) : base(httpClientFactory)
    {
        RemoteApiUrl  = AppSettings.GetValue("IMSApiAddress");
    }
    #region 调度

   





    /// <summary>
    /// 提交叠盘完成
    /// </summary>
    /// <param name="tagNumber"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    [QueryParameters]
    public async Task<string> CommitStackOver(int tagNumber)
    {
        var client = CreateHttpClient();
        string url = $"{_apiHead}/tray/stack/notify/{tagNumber}?";
        var result = await client.GetFmsData<string>(url, null);

        if (result.Success)
        {
            return string.Empty;
        }
        else
        {

            throw Oops.Oh(result.Message);
        }
    }
    /// <summary>
    /// 完成任务
    /// </summary>
    /// <param name="job"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<string> CompleteJob(FmsJobCompleteRequest job)
    {
        var client = CreateHttpClient();
        string url = $"{_apiHead}/tray/task/notify";
        var result = await client.PostFmsData<string>(url, job);

        if (!result.Success)
        {
            throw Oops.Oh(result.Message);
        }
        return string.Empty;
    }

    /// <summary>
    /// 扫码后提交托盘
    /// </summary>
    /// <param name="unit"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<CvTrayTask> CommitTrays(FmsCommitTrayRequest unit)
    {

        var client = CreateHttpClient();
        string url = $"{_apiHead}/tray/transfer?";
        var result = await client.PostFmsData<FmsTransferResponse>(url, new FmsTransferRequest
        {
            ConveyorCode = unit.TagNumber.ToString(),
            TaskNo = unit.TaskNo,
            Trays = unit.Trays
        });

        if (result.Success)
        {
            var fms = new CvTrayTask
            {
                Dest = result.Result.DesCvCode,
                TagNumber = result.Result.OriCvCode,
                TaskNum = result.Result.TaskNumber,
                TrayType = result.Result.StackType
            };
            return fms;

        }
        else
        {
            throw Oops.Oh(result.Message);
        }
    }
    /// <summary>
    /// 站台提交扫码
    /// </summary>
    /// <param name="unitGroup"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)] 
    public async Task<F29EnterJob> CommitEnterTrays(FmsCommitTrayRequest unitGroup)
    {
        FmsEnterTransferRequest request = new FmsEnterTransferRequest
        {
            Cvs = new List<FmsCv>()

        };
      
        if (unitGroup.TagNumber>0)
        {
            request.Cvs.Add(new FmsCv
            {
                ConveyorCode = unitGroup.TagNumber.ToString(),
                Trays = unitGroup.Trays,
                ForkType = 1,
                TaskNumber = unitGroup.TaskNo
            });
        }

        if (unitGroup.TagNumber2>0)
        {
            request.Cvs.Add(new FmsCv
            {
                ConveyorCode = unitGroup.TagNumber2.ToString(),
                Trays = unitGroup.Trays2,
                ForkType = 2,
                TaskNumber = unitGroup.TaskNo
            });
        }
        var unit = request.Cvs.FirstOrDefault();
        var client = CreateHttpClient();
        string url = $"{_apiHead}/tray/inbound?";
        var result = await client.PostFmsData<FmsEnterScResponse>(url, request);

        if (result.Success)
        {
            var fms = new F29EnterJob
            {
                EquipNum = result.Result.StackerCode,
                FromTagNumber = result.Result.FromTagNumber.To<int>(),
                JobID = result.Result.TaskNumberId,
                FromX = result.Result.FromR,
                FromY = result.Result.FromC,
                FromZ = result.Result.FromF,
                ToX = result.Result.ToR,
                ToY = result.Result.ToC,
                ToZ = result.Result.ToF,
                FromTagNumber2 = result.Result.FromTagNumber2,
                FromX2 = result.Result.FromR2,
                FromY2 = result.Result.FromC2,
                FromZ2 = result.Result.FromF2,
                ToX2 = result.Result.ToR2,
                ToY2 = result.Result.ToC2,
                ToZ2 = result.Result.ToF2,
                UsePoke = result.Result.UsePoke,
                JobID2 = result.Result.TaskNumberId2,
                Num = result.Result.StackerCode,
                Tray = result.Result.Tray,
                Tray2 = result.Result.Tray2,
                RightTray = result.Result.rTray,
                RightTray2 = result.Result.rTray2

            };
            return fms;

        }
        else
        {
           

           throw Oops.Oh(result.Message);
        }
    }


    /// <summary>
    /// 获取换盘数据通道
    /// </summary>
    /// <param name="fmsTray"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<List<FMTCell>> GetCebChannel(FmsTrayRequest fmsTray)
    {

        var client = CreateHttpClient();
        string url = $"{_apiHead}/change-disc/tray-enter-work";
        var result = await client.PostFmsData<List<FMTCell>>(url, fmsTray);

        if (!result.Success)
        {
            throw Oops.Oh(result.Message);
        }
        return result.Result;
    }

    /// <summary>
    /// 换盘结束通知
    /// </summary>
    /// <param name="fmsTray"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<string> CebWorkDoneInform(FmsTrayRequest fmsTray)
    {

        var client = CreateHttpClient();
        string url = $"{_apiHead}/change-disc/tray-out-inform";
        var result = await client.PostFmsData<string>(url, fmsTray);

        if (!result.Success)
        {
            throw Oops.Oh(result.Message);
        }

        return string.Empty ;
    }
    /// <summary>
    /// 验证换盘机拖盘进入
    /// </summary>
    /// <param name="fmsTray"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<string> ValidateCebEnterTray(FmsTrayRequest fmsTray)
    {

        var client = CreateHttpClient();
        string url = $"{_apiHead}/change-disc/commit-tray-enter";
        var result = await client.PostFmsData<string>(url, fmsTray);

        if (!result.Success)
        {
            throw Oops.Oh(result.Message);
        }
        return string.Empty;
    }
    /// <summary>
    /// 验证换盘机出去
    /// </summary>
    /// <param name="fmsTray"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<string> ValidateCebOutTray(FmsTrayRequest fmsTray)
    {

        var client = CreateHttpClient();
        string url = $"{_apiHead}/change-disc/commit-tray-leave";
        var result = await client.PostFmsData<string>(url, fmsTray);

        if (!result.Success)
        {
            throw Oops.Oh(result.Message);
        }

        return string.Empty;
    }

    /// <summary>
    /// 验证托盘进入
    /// </summary>
    /// <param name="lgTrayEnter"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<string> ValidateEnterTray(LgTrayEnterRequest lgTrayEnter)
    {

        var client = CreateHttpClient();
        string url = $"{_apiHead}/common/skip-record-start";
        var result = await client.PostFmsData<string>(url, new FmsTrayRequest { EquipNum = lgTrayEnter.EquipNum, Tray = lgTrayEnter.Tray });
        if (!result.Success)
        {
            throw Oops.Oh(result.Message);
        }
        return string.Empty;
    }

    /// <summary>
    /// 验证托盘出去
    /// </summary>   
    /// <param name="lgTrayOut"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Tag = IotApiConst.Process)]
    public async Task<string> ValidateOutTray(LgTrayOutRequest lgTrayOut)
    {

        var client = CreateHttpClient();
        string url = $"{_apiHead}/common/skip-record-end";
        var result = await client.PostFmsData<string>(url, new FmsTrayRequest { EquipNum = lgTrayOut.EquipNum, Tray = lgTrayOut.Tray });
        if (!result.Success)
        {
            throw Oops.Oh(result.Message);
        }
        return string.Empty;
    }

    #endregion
}
